<script lang="ts" setup name="Room">
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { onMounted, onUnmounted, ref, nextTick, provide } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRoute } from 'vue-router'
import { getConsultOrderDetail } from '@/api/consult'
import type { ConsultOrderItem, Message, TimeMessage, Image } from '@/types/consult'
import RoomStatus from './components/room-status.vue'
import RoomMessage from './components/room-message.vue'
import RoomAction from './components/room-action.vue'
import dayjs from 'dayjs'
// 页面中，枚举前面不需要加type
import { OrderType, MsgType } from '@/enums'
import { showToast } from 'vant'
const consultOrderDetail = ref({} as ConsultOrderItem)
const store = useUserStore()
const route = useRoute()
const list = ref<Message[]>([])
// 每次加载历史消息的时间点
let time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const loading = ref(false)
const initialMsg = ref(true)

let socket: Socket
onMounted(async () => {
  //1、创建跟服务器的socket连接
  /**
   * 参数1：基地址
   * 参数2：auth授权信息
   * 参数3：连接参数
   */
  socket = io(import.meta.env.VITE_APP_BASE_URL, {
    auth: {
      token: `Bearer ${store.user.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  // 2、一进入页面，查询问诊订单的状态
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consultOrderDetail.value = res.data

  // 医生接诊之后，会触发statusChange事件，在它里面重新获取订单状态
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consultOrderDetail.value = res.data
  })

  socket.on('connect', () => {
    // console.log('---连接成功---')
    socket.on('chatMsgList', ({ data }: { data: TimeMessage[] }) => {
      console.log('---data---', data)
      // data中的元素，现在是1个元素
      const tempArray: Message[] = []
      data.forEach((item, i) => {
        if (i === 0) time.value = item.createTime
        // 在服务器返回的消息列表前，加上一个时间消息
        tempArray.push({
          id: item.createTime,
          msgType: MsgType.Notify,
          createTime: item.createTime,
          msg: {
            content: item.createTime
          }
        })

        tempArray.push(...item.items)
      })

      // 把它放在，最终需要渲染的list数组中去
      // 这里面一定要用unshift，因为我们将来还要加载历史消息
      list.value.unshift(...tempArray)

      loading.value = false
      if (data.length === 0) {
        showToast('没有聊天记录啦~')
      }
      console.log('---默认消息列表---', list.value)

      nextTick(() => {
        // 等数据渲染完了，滚动到最底部
        if (initialMsg.value) {
          window.scroll(0, document.body.scrollHeight)
          initialMsg.value = false
        }
      })
    })
  })

  // 监听服务器返回的数据
  socket.on('receiveChatMsg', async event => {
    console.log('---event---', event)
    list.value.push(event)

    await nextTick()
    window.scroll(0, document.body.scrollHeight)
  })

  socket.on('error', event => {
    // 错误异常消息
    console.log('---error---', event)
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })
})

// 发送文字消息
const sendText = (content: string) => {
  // 发送消息需要 发送人、收消息人，消息类型，消息内容
  socket.emit('sendChatMsg', {
    from: store.user.id,
    to: consultOrderDetail.value.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content
    }
  })
}

// 发送图片消息
const sendImage = (picture: Image) => {
  // 发送消息需要 发送人、收消息人，消息类型，消息内容
  socket.emit('sendChatMsg', {
    from: store.user.id,
    to: consultOrderDetail.value.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture
    }
  })
}

// 下拉刷新，加载历史聊天记录
const onRefresh = () => {
  /**
   * 参数1：事件名称
   * 参数2：加载多少条数据
   * 参数3：时间戳（该时间之前）
   * 参数4：订单号
   */
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

onUnmounted(() => {
  // 节约资源
  socket && socket.close()
})

// 把之前的未评价，变成已评价
const updateEvaluateDoc = (score: number) => {
  const evaluateDoc = list.value.find(item => item.msgType === MsgType.CardEvaForm)
  if (evaluateDoc) {
    evaluateDoc.msgType = MsgType.CardEva
    evaluateDoc.msg.evaluateDoc = {
      score
    }
  }
}

provide('consultOrderDetail', consultOrderDetail)
provide('updateEvaluateDoc', updateEvaluateDoc)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consultOrderDetail.status" :countdown="consultOrderDetail.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list" />
    </van-pull-refresh>
    <room-action
      :disabled="consultOrderDetail.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
